package com.nuoniu.sibanyun.service.RSA;

import com.nuoniu.sibanyun.common.codec.RSAUtils;
import com.nuoniu.sibanyun.common.constant.AttributeConstant;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.service.redis.RedisService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;

import java.security.KeyPair;

/**
 * @ClassName RsaService
 * @Description TODO
 * @Authpr baiqiang
 * @Date 2020/6/4 14:37
 **/
@Service
@Log4j2
public class RsaService {

    @Autowired
    private RedisService redisService;

    /**
     * 获取 公钥
     * @return
     */
    public String getPublicKey() {
        String privateKey = redisService.getAsString(AttributeConstant.RSA_PRIVATE_KEY);
        String publicKey = redisService.getAsString(AttributeConstant.RSA_PUBLIC_KEY);
        if (StringUtils.isBlank(publicKey) || StringUtils.isBlank(privateKey)) {
            KeyPair keyPair;
            try {
                keyPair = RSAUtils.getKeyPair();
            } catch (Exception e) {
                e.printStackTrace();
                throw new NuoNiuException("RHA获取密钥对失败");
            }
            privateKey = new String(Base64Utils.encode(keyPair.getPrivate().getEncoded()));
            publicKey = new String(Base64Utils.encode(keyPair.getPublic().getEncoded()));
            redisService.set(AttributeConstant.RSA_PRIVATE_KEY, privateKey);
            redisService.set(AttributeConstant.RSA_PUBLIC_KEY, publicKey);
        }
        log.info("privateKey = {},publicKey = {}",privateKey,publicKey);
        return publicKey;
    }

    /**
     * RSA解密
     * @param key
     * @return
     */
    public String decrypt(String key){
        String privateKey = redisService.getAsString(AttributeConstant.RSA_PRIVATE_KEY);
        try {
            String decryptStr = RSAUtils.decrypt(key,RSAUtils.getPrivateKey(privateKey));
            return decryptStr;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
